<?php
/**
 * SESSION类
 * @author wangtao
 * @version 2010.11.17
 */

class SESSION
{
	private $db;
	function __construct($db)
	{
		$this->db = $db;
		$this->gc(3600);
	}

	/**
	 * 打开session
	 * @param string $save_path		保存路径
	 * @param string $session_name	session路径
	 */
	public function open($save_path,$session_name)
	{
		return true;
	}

	/**
	 * 关闭session
	 */
	public function close()
	{
		#$this->db=null;
		return true;
	}

	/**
	 * session读取,传值SID,在数据表中将这个SID的VALUE作为返回值返回;
	 * @param string $sid	SID
	 */
	public function read($id)
	{
		$sql = 'SELECT `value` FROM `sessions` WHERE `sid` = \'' . $id . '\'';
		$rs = $this->db->query2one($sql);
		if (!empty($rs))
		{
			return $rs;
		}
		else
		{
			return null;
		}
	}
	
	/**
	 * 
	 * @param string $sid
	 * @param string $value
	 */
	public function write($id, $sess_data)
	{
		$sql = 'SELECT `value` FROM `sessions` WHERE `sid` = \'' . $id . '\'';
		$oldvalue = $this->db->SQLnum($sql);
		if(!$oldvalue)
		{
			//inser
			$time = date('Y-m-d H:i:s');
			$sql = 'INSERT INTO `sessions` (`sid`, `expiry`, `value`) VALUES (\'' . $id . '\', \'' . $time . '\', \'' . $sess_data . '\');';
			return $this->db->query($sql);
		}
		else
		{
			//update
			$sql = 'UPDATE `sessions` SET `value` = \'' . $sess_data . '\' WHERE `sessions`.`sid` = \'' . $id . '\';';
			return $this->db->query($sql);
		}
	}
	
	/**
	 * session的销毁
	 * @param int $sid
	 */
	public function destroy($id)
	{
		$sql = 'DELETE FROM `sessions` WHERE `sessions`.`sid` = \'' . $id . '\'';
		return $this->db->query($sql);
	}
	
	/**
	 * 清空过期session,把超过max_life_time的SESSION都销毁掉
	 * @param unknown_type $max_life_time
	 */
	public function gc($maxlifetime)
	{
		$time = date('Y-m-d H:i:s');
		$sql = 'DELETE FROM `sessions` WHERE FROM_UNIXTIME((UNIX_TIMESTAMP(`expiry`) +' . $maxlifetime . ' ) , 
		\'%Y-%m-%d %H:%i:%s\')<\'' . $time . '\'';
		return $this->db->query($sql);
	}
}